package cn.iocoder.yudao.module.blog.service.component;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.blog.controller.admin.component.vo.*;
import cn.iocoder.yudao.module.blog.dal.dataobject.component.BlogComponentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.blog.convert.component.BlogComponentConvert;
import cn.iocoder.yudao.module.blog.dal.mysql.component.BlogComponentMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.blog.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 置顶案例 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class BlogComponentServiceImpl implements BlogComponentService {

    @Resource
    private BlogComponentMapper componentMapper;

    @Override
    public Long createComponent(BlogComponentCreateReqVO createReqVO) {
        // 插入
        BlogComponentDO component = BlogComponentConvert.INSTANCE.convert(createReqVO);
        componentMapper.insert(component);
        // 返回
        return component.getId();
    }

    @Override
    public void updateComponent(BlogComponentUpdateReqVO updateReqVO) {
        // 校验存在
        validateComponentExists(updateReqVO.getId());
        // 更新
        BlogComponentDO updateObj = BlogComponentConvert.INSTANCE.convert(updateReqVO);
        componentMapper.updateById(updateObj);
    }

    @Override
    public void deleteComponent(Long id) {
        // 校验存在
        validateComponentExists(id);
        // 删除
        componentMapper.deleteById(id);
    }

    private void validateComponentExists(Long id) {
        if (componentMapper.selectById(id) == null) {
            throw exception(COMPONENT_NOT_EXISTS);
        }
    }

    @Override
    public BlogComponentDO getComponent(Long id) {
        return componentMapper.selectById(id);
    }

    @Override
    public List<BlogComponentDO> getComponentList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return componentMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlogComponentDO> getComponentPage(BlogComponentPageReqVO pageReqVO) {
        return componentMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BlogComponentDO> getComponentList(BlogComponentExportReqVO exportReqVO) {
        return componentMapper.selectList(exportReqVO);
    }

    @Override
    public List<BlogComponentDO> getAll(String type){
        return componentMapper.selectList(BlogComponentDO::getType, type);
    }
}
